package com.daye.dao;

import com.daye.entity.Account;
import com.daye.entity.Transaction;
import com.daye.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class AccountDao {

    public List<Account> getAllAccount() throws SQLException {
        QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());

        String sql = "select * from account";
        return qr.query(sql , new BeanListHandler<Account>(Account.class));
    }

    /**
     * 使用连接池创建QueryRunner对象；
     * 判断转出方是否有足够余额，如果不足，提示信息：”余额不足！”，并结束程序；
     * @param card
     * @return
     */
    public Account getAccountByCardNum(String card) throws SQLException {
        QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());
        String sql = "SELECT * FROM account WHERE card = ? ";
        return qr.query(sql , new BeanHandler<Account>(Account.class) , card);
    }

    /**
     * 通过卡号 进行转账的操作；
     * @param srcCard
     * @param targetCard
     * @param money
     * @return
     */
    public boolean transferMoneyByCard(String srcCard, String targetCard, double money) throws SQLException {
        QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());
        Connection connection = DruidUtils.getConnection();
        //开启事务
        connection.setAutoCommit(false);
        String sql = "UPDATE account SET balance = balance - ? WHERE card = ?";
        if (qr.update(sql, money, srcCard) <= 0){
            //操作失败
            connection.rollback();
            return false;
        };

        sql = "UPDATE account SET balance = balance + ? WHERE card = ?";
        if (qr.update(sql , money , targetCard) <= 0){
            //操作失败
            connection.rollback();
            return false;
        }

        connection.commit();
        return true;
    }

    /**
     * 转账结束后, 将转入、转出记录分别写入到Transaction表中。
     * @param out
     * @param in
     * @return
     */
    public Boolean saveTransferTransaction(Transaction out, Transaction in) throws SQLException {
        QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());
        Connection connection = DruidUtils.getConnection();

        //开启事务
        connection.setAutoCommit(false);

        String sql = "INSERT INTO TRANSACTION(cardid , tratype , tramoney , tradate ) VALUES(? , ? , ? , ?)";
        Object[] outParma = {out.getCardid() , out.getTratype() , out.getTramoney() , out.getTradate()};
        if (qr.update(sql, outParma) <= 0){
            connection.rollback();
            return false;
        }

        Object[] inParma = {in.getCardid() , in.getTratype() , in.getTramoney() , in.getTradate()};
        if (qr.update(sql, inParma) <= 0){
            connection.rollback();
            return false;
        }

        connection.commit();
        return true;
    }
}
